package org.wu.spring.orm.integration.compare.infrastructure.persistence.jdbc;


import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import org.wu.framework.core.NormalUsedString;
import org.wu.framework.lazy.orm.database.lambda.domain.LazyPage;
import org.wu.framework.web.response.Result;
import org.wu.framework.web.response.ResultFactory;
import org.wu.spring.orm.integration.compare.domain.model.sys.user.SysUser;
import org.wu.spring.orm.integration.compare.infrastructure.persistence.SysUserRepositoryAbstractRecord;
import org.wu.spring.orm.integration.compare.infrastructure.persistence.enums.Orm;
import org.wu.spring.orm.integration.compare.infrastructure.persistence.enums.Type;

import javax.sql.DataSource;
import java.sql.*;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * describe sys_user
 *
 * @author Jia wei Wu
 * @date 2024/02/28 11:27 上午
 * @see org.wu.framework.lazy.orm.core.persistence.reverse.lazy.ddd.DefaultDDDLazyInfrastructurePersistence
 **/
@Component("jdbcComparisonRepository")
public class JdbcComparisonRepository extends SysUserRepositoryAbstractRecord {


    @Resource
    private DataSource dataSource;

    /**
     * describe 新增
     *
     * @param sysUser 新增
     * @return {@link Result<SysUser>} 新增后领域对象
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<SysUser> story(SysUser sysUser) throws Exception {
        boolean success = true;
        super.resetTestTableRecords();
        LocalDateTime startTime = LocalDateTime.now();
        Connection connection = null;
        try {

            connection = dataSource.getConnection();
            connection.setAutoCommit(true);
            PreparedStatement preparedStatement =
                    connection
                            .prepareStatement(
                                    "INSERT INTO `sys_user` (`column_name`, `create_time`, `id`, `is_deleted`, `password`, `scope`, `status`, `update_time`, `username`) VALUES (?,?,?,?,?,?,?,?,?)");

            preparedStatement.setString(1, sysUser.getColumnName());
            preparedStatement.setDate(2, Date.valueOf(sysUser.getCreateTime().toLocalDate()));
            preparedStatement.setLong(3, sysUser.getId());
            preparedStatement.setBoolean(4, sysUser.getIsDeleted());
            preparedStatement.setString(5, sysUser.getPassword());
            preparedStatement.setString(6, sysUser.getScope());
            preparedStatement.setBoolean(7, sysUser.getStatus());
            preparedStatement.setDate(8, Date.valueOf(sysUser.getUpdateTime().toLocalDate()));
            preparedStatement.setString(9, sysUser.getUsername());
            preparedStatement.executeUpdate();
            preparedStatement.close();

        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        } finally {
            if (connection != null) {
                connection.close();
            }
        }

        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.JDBC, Type.story, startTime, endTime, success);
        return ResultFactory.successOf();
    }

    /**
     * describe 批量新增
     *
     * @param sysUserList 批量新增
     * @return {@link Result<List<SysUser>>} 新增后领域对象集合
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<List<SysUser>> batchStory(List<SysUser> sysUserList) throws Exception {
        boolean success = true;
        super.resetTestTableRecords();
        LocalDateTime startTime = LocalDateTime.now();
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);
            String sql = "INSERT INTO `sys_user` (`column_name`, `create_time`, `id`, `is_deleted`, `password`, `scope`, `status`, `update_time`, `username`) VALUES";

            String valueSql = sysUserList.stream().map(sysUser -> "("+
                    sysUser.getColumnName()+"," +
                    sysUser.getCreateTime()+"," +
                    sysUser.getId()+"," +
                    sysUser.getIsDeleted()+"," +
                    sysUser.getPassword()+"," +
                    sysUser.getScope()+"," +
                    sysUser.getStatus()+"," +
                    sysUser.getUpdateTime()+"," +
                    sysUser.getUsername() +

                    ")").collect(Collectors.joining(NormalUsedString.COMMA));
            PreparedStatement preparedStatement =
                    connection
                            .prepareStatement(sql +valueSql);
//            for (SysUser sysUser : sysUserList) {
//                preparedStatement.setString(1, sysUser.getColumnName());
//                preparedStatement.setDate(2, Date.valueOf(sysUser.getCreateTime().toLocalDate()));
//                preparedStatement.setLong(3, sysUser.getId());
//                preparedStatement.setBoolean(4, sysUser.getIsDeleted());
//                preparedStatement.setString(5, sysUser.getPassword());
//                preparedStatement.setString(6, sysUser.getScope());
//                preparedStatement.setBoolean(7, sysUser.getStatus());
//                preparedStatement.setDate(8, Date.valueOf(sysUser.getUpdateTime().toLocalDate()));
//                preparedStatement.setString(9, sysUser.getUsername());
//                preparedStatement.addBatch();
//            }
            preparedStatement.executeLargeBatch();
            connection.commit();
            preparedStatement.close();
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        } finally {
            if (connection != null) {
                connection.close();
            }
        }

        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.JDBC, Type.batchStory, startTime, endTime, sysUserList.size(), success);
        return ResultFactory.successOf();
    }

    /**
     * describe 查询单个
     *
     * @param sysUser 查询单个
     * @return {@link Result<SysUser>} 领域对象
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<SysUser> findOne(SysUser sysUser) throws Exception {
        boolean success = true;
        super.findOne(sysUser);
        LocalDateTime startTime = LocalDateTime.now();


        Connection connection = null;
        ResultSet resultSet = null;
        Statement statement = null;

        try {

            connection = dataSource.getConnection();

            statement = connection.createStatement();

            resultSet = statement.executeQuery("SELECT * FROM `sys_user` WHERE `id` = " + sysUser.getId());
            boolean next = resultSet.next();
            SysUser single = new SysUser();
            if (next) {
                String columnName = resultSet.getString("column_name");
                Date createTime = resultSet.getDate("create_time");
                long id = resultSet.getLong("id");
                boolean isDeleted = resultSet.getBoolean("is_deleted");
                String password = resultSet.getString("password");
                String scope = resultSet.getString("scope");
                boolean status = resultSet.getBoolean("status");
                Date updateTime = resultSet.getDate("update_time");
                String username = resultSet.getString("username");

                single.setId(id);
                single.setColumnName(columnName);
                single.setCreateTime(LocalDateTime.ofInstant(createTime.toInstant(), ZoneId.systemDefault()));
                single.setIsDeleted(isDeleted);
                single.setPassword(password);
                single.setScope(scope);
                single.setStatus(status);
                single.setUpdateTime(LocalDateTime.ofInstant(updateTime.toInstant(), ZoneId.systemDefault()));
                single.setUsername(username);

            }
            return ResultFactory.successOf(single);
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        } finally {
            if (statement != null) {
                statement.close();
            }
            if (resultSet != null) {
                resultSet.close();
            }
            if (connection != null) {
                connection.close();
            }
            LocalDateTime endTime = LocalDateTime.now();
            storyRecord(Orm.JDBC, Type.findOne, startTime, endTime, success);
        }

        return ResultFactory.successOf();
    }

    /**
     * describe 查询多个
     *
     * @param sysUser 查询多个
     * @return {@link Result<List<SysUser>>} 领域对象
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<List<SysUser>> findList(SysUser sysUser) throws Exception {
        boolean success = true;
        super.findList(sysUser);
        LocalDateTime startTime = LocalDateTime.now();


        Connection connection = null;
        ResultSet resultSet = null;
        Statement statement = null;

        try {

            connection = dataSource.getConnection();

            statement = connection.createStatement();

            resultSet = statement.executeQuery("SELECT * FROM `sys_user` ");

            List<SysUser> sysUserList = new ArrayList<>();

            while (resultSet.next()) {
                SysUser single = new SysUser();
                String columnName = resultSet.getString("column_name");
                Date createTime = resultSet.getDate("create_time");
                long id = resultSet.getLong("id");
                boolean isDeleted = resultSet.getBoolean("is_deleted");
                String password = resultSet.getString("password");
                String scope = resultSet.getString("scope");
                boolean status = resultSet.getBoolean("status");
                Date updateTime = resultSet.getDate("update_time");
                String username = resultSet.getString("username");

                single.setId(id);
                single.setColumnName(columnName);
                single.setCreateTime(createTime.toLocalDate().atTime(LocalTime.MIDNIGHT));
                single.setIsDeleted(isDeleted);
                single.setPassword(password);
                single.setScope(scope);
                single.setStatus(status);
                single.setUpdateTime(updateTime.toLocalDate().atTime(LocalTime.MIDNIGHT));
                single.setUsername(username);
                sysUserList.add(single);
            }

            return ResultFactory.successOf(sysUserList);
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        } finally {
            if (statement != null) {
                statement.close();
            }
            if (resultSet != null) {
                resultSet.close();
            }
            if (connection != null) {
                connection.close();
            }
            LocalDateTime endTime = LocalDateTime.now();
            storyRecord(Orm.JDBC, Type.findList, startTime, endTime, success);
        }

        return ResultFactory.successOf();

    }

    /**
     * describe 分页查询多个
     *
     * @param size    当前页数
     * @param current 当前页
     * @param sysUser 分页查询多个
     * @return {@link Result<LazyPage<SysUser>>} 分页领域对象
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<LazyPage<SysUser>> findPage(int size, int current, SysUser sysUser) throws Exception {
        boolean success = true;
        super.findList(sysUser);

        LocalDateTime startTime = LocalDateTime.now();


        Connection connection = null;
        ResultSet resultSet = null;
        Statement statement = null;

        try {

            connection = dataSource.getConnection();

            statement = connection.createStatement();

            resultSet = statement.executeQuery("SELECT * FROM `sys_user` limit " + current + "," + size);

            List<SysUser> sysUserList = new ArrayList<>();

            while (resultSet.next()) {
                SysUser single = new SysUser();
                String columnName = resultSet.getString("column_name");
                Date createTime = resultSet.getDate("create_time");
                long id = resultSet.getLong("id");
                boolean isDeleted = resultSet.getBoolean("is_deleted");
                String password = resultSet.getString("password");
                String scope = resultSet.getString("scope");
                boolean status = resultSet.getBoolean("status");
                Date updateTime = resultSet.getDate("update_time");
                String username = resultSet.getString("username");

                single.setId(id);
                single.setColumnName(columnName);
                single.setCreateTime(createTime.toLocalDate().atTime(LocalTime.MIDNIGHT));
                single.setIsDeleted(isDeleted);
                single.setPassword(password);
                single.setScope(scope);
                single.setStatus(status);
                single.setUpdateTime(updateTime.toLocalDate().atTime(LocalTime.MIDNIGHT));
                single.setUsername(username);
                sysUserList.add(single);
            }

            LazyPage<SysUser> lazyPage = LazyPage.of(current, size);
            lazyPage.setRecord(sysUserList);
            return ResultFactory.successOf(lazyPage);
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        } finally {
            if (statement != null) {
                statement.close();
            }
            if (resultSet != null) {
                resultSet.close();
            }
            if (connection != null) {
                connection.close();
            }
            LocalDateTime endTime = LocalDateTime.now();
            storyRecord(Orm.JDBC, Type.findPage, startTime, endTime, size,success);
        }

        return ResultFactory.successOf();
    }

    /**
     * describe 删除
     *
     * @param sysUser 删除
     * @return {@link Result<SysUser>}
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<SysUser> remove(SysUser sysUser) throws Exception {
        boolean success = true;
        super.remove(sysUser);
        LocalDateTime startTime = LocalDateTime.now();


        Connection connection = null;
        Statement statement = null;

        try {

            connection = dataSource.getConnection();

            statement = connection.createStatement();

            statement.executeUpdate("delete from `sys_user` where id = " + sysUser.getId());


        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        } finally {
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        }

        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.JDBC, Type.remove, startTime, endTime, success);
        return ResultFactory.successOf();
    }

    /**
     * describe 是否存在
     *
     * @param sysUser 领域对象
     * @return {@link Result<Boolean>} 是否存在 true 存在，false 不存在
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<Boolean> exists(SysUser sysUser) throws Exception {
        boolean success = true;
        super.exists(sysUser);
        boolean exists = false;
        LocalDateTime startTime = LocalDateTime.now();


        Connection connection = null;
        Statement statement = null;

        try {

            connection = dataSource.getConnection();

            statement = connection.createStatement();

            statement.executeQuery("select count(1) from `sys_user` where id = " + sysUser.getId());


        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        } finally {
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        }

        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.JDBC, Type.exists, startTime, endTime, success);
        return ResultFactory.successOf(exists);
    }

}